from rest_framework import serializers
from .models import Inform,InformRead
from apps.oaauth.serializers import UserSerializer,DeptSerializer
from apps.oaauth.models import OADepartment

class  InformReadSerializer(serializers.ModelSerializer):
    class Meta:
        model = InformRead
        fields = '__all__'
class InformSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    department = DeptSerializer(many=True,  read_only=True)
    # 部门id是包含部门的列表，后端需要接受列表，所以需要ListSerializer
    department_id = serializers.ListSerializer(child=serializers.IntegerField(), write_only=True)
    reads = InformReadSerializer(many=True, read_only=True)
    create_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d')
    class Meta:
        model = Inform
        fields = '__all__'
        read_only_fields= ['public']

    def create(self, validated_data):
        request = self.context['request']
        author = request.user
        department_id = validated_data.pop('department_id')
        #对列表中的值d都转换为int操作，使用map函数
        def toInt(value):
            return int(value)
        department_id = list(map(toInt,department_id))
        if 0 in department_id:
            inform = Inform.objects.create(public=True, author= author,  **validated_data)
        else:
            department = OADepartment.objects.filter(id__in=department_id).all()
            inform = Inform.objects.create(author=author, public=False, **validated_data)
            #将 inform 实例的 department 多对多关系设置为传入的 department 列表
            inform.department.set(department)
            inform.save()
        return inform

class ReadInformSerializer(serializers.Serializer):
    inform_pk = serializers.IntegerField(error_messages={'required': '请传入通知id'})





